import React, { useState } from "react";
import './style.css'

const PictureCard = (props) => {
    const { uploadImage,word } = props;
    const [imgPreview, setImgPreview] = useState('https://res.bearbobo.com/resource/upload/W44yyxvl/upload-ih56twxirei.png');
    const updateImageData = (e) => {
        // html5 的文件上传功能
        const file = e.target.files?.[0]; // 可选链操作符
        if(!file) {
            return;
        }
        // 图片预览 I/O操作 异步
        return new Promise((resolve,reject) => {
            // html5
            const reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = (e) => {
                // 响应式业务
                setImgPreview(reader.result);
                // 如何将图片数据交给父组件
                uploadImage(reader.result);
                resolve(reader.result);
            }
            reader.onerror = () => {
                reject(reader.error);
            }
        })
    }
  return (
    <div className='card'>
      <input 
      type="file" 
      id="selectImage" 
      accept=".jpg,.jpeg,.png,.gif"
      onChange={updateImageData}
      />
      <label htmlFor="selectImage" className="selectImage">
        <img src={imgPreview} alt="preview" />
      </label>
      {/* template -> JSX -> {数据绑定} -> 响应式 -> 单词业务 */}
      <div className="word">{word}</div>
    </div>
  )
}

export default PictureCard